<template>
  <div class="user-management">
    <el-breadcrumb separator="/" class="breadcrumb">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="header">
      <div class="search">
        <el-input v-model="searchName" placeholder="请输入姓名搜索" class="search-input" clearable />
        <el-input v-model="searchMobile" placeholder="请输入手机号搜索" class="search-input" clearable />
        <el-button type="primary" @click="handleSearch" :icon="Search" class="search-button">搜索</el-button>
      </div>
      <div class="actions">
        <el-button type="primary" @click="fetchUsers" :icon="RefreshRight">刷新列表</el-button>
        <el-button type="success" @click="showAddForm" :icon="Plus">添加用户</el-button>
      </div>
    </div>
    
    <el-table :data="users" class="user-table" border>
      <el-table-column prop="id" label="ID" min-width="80" align="center"></el-table-column>
      <el-table-column prop="userName" label="用户姓名" min-width="120" align="center"></el-table-column>
      <el-table-column prop="userAvatar" label="头像" min-width="150" align="center">
        <template #default="scope">
          <el-avatar :src="scope.row.userAvatar" shape="circle" fit="cover" />
        </template>
      </el-table-column>
      <el-table-column prop="userGender" label="性别" min-width="80" align="center">
        <template #default="scope">
          <span v-if="scope.row.userGender === 1">男</span>
          <span v-else-if="scope.row.userGender === 0">女</span>
          <span v-else>未知</span>
        </template>
      </el-table-column>
      <el-table-column prop="userMobile" label="手机号" min-width="120" align="center"></el-table-column>
      <el-table-column prop="userEmail" label="邮箱" min-width="150" align="center"></el-table-column>
      <el-table-column prop="userDeptName" label="部门名称" min-width="120" align="center"></el-table-column>
      <el-table-column prop="userStatus" label="账号状态" min-width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.userStatus ? 'danger' : 'success'">{{ scope.row.userStatus ? '禁用' : '正常' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="userBirthday" label="生日" min-width="120" align="center">
        <template #default="scope">
          {{ scope.row.userBirthday ? $filters.formatDate(scope.row.userBirthday) : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="userJoinAt" label="入职时间" min-width="120" align="center">
        <template #default="scope">
          {{ scope.row.userJoinAt ? $filters.formatDate(scope.row.userJoinAt) : '' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="200" fixed="right" align="center">
        <template #default="scope">
          <el-button size="small" type="primary" @click="showEditForm(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteUser(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
      <template #empty>
        <div class="empty-placeholder">
          <div class="empty-icon">
            <svg xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 1024 1024" height="128px" width="128px"> 
              <defs> 
                <linearGradient id="linearGradient-1" y2="50%" x2="50%" y1="0%" x1="50%"> 
                  <stop offset="0%" stop-color="#E6F2FF"></stop> 
                  <stop offset="100%" stop-opacity="0" stop-color="#E3EFFD"></stop> 
                </linearGradient> 
                <path id="path-2" d="M0,0 L512,0 L512,236.8 C512,250.93849 500.53849,262.4 486.4,262.4 L25.6,262.4 C11.4615104,262.4 -7.10542736e-15,250.93849 -7.10542736e-15,236.8 L0,0 L0,0 Z"></path> 
                <linearGradient id="linearGradient-4" y2="6.16297582e-31%" x2="50%" y1="100%" x1="50%"> 
                  <stop offset="0%" stop-color="#99D1FC"></stop> 
                  <stop offset="100%" stop-color="#60A4F7"></stop> 
                </linearGradient> 
              </defs> 
              <g fill-rule="evenodd" fill="none" stroke-width="1" stroke="none"> 
                <ellipse ry="115.2" rx="416" cy="707.2" cx="512" fill="url(#linearGradient-1)" id="椭圆形"></ellipse> 
                <g transform="translate(233.6, 163.2)"> 
                  <g transform="translate(41.6, 131.2)"> 
                    <mask fill="white" id="mask-3"> 
                      <use xlink:href="#path-2"></use> 
                    </mask> 
                    <use xlink:href="#path-2" fill="#D8EBFA"></use> 
                    <rect height="262.4" width="214.4" y="0" x="297.6" mask="url(#mask-3)" fill="#60A4F7"></rect> 
                  </g> 
                  <rect rx="6.4" height="12.8" width="57.6" y="320" x="118.4" fill="#60A4F7" id="矩形备份-2"></rect> 
                  <path fill="#B8DAFF" id="形状结合" d="M483.2,131.2 L483.2,291.2 L483.039812,291.200785 C482.298276,294.851978 479.070055,297.6 475.2,297.6 C471.329945,297.6 468.101724,294.851978 467.360188,291.200785 L463.839812,291.200785 C463.098276,294.851978 459.870055,297.6 456,297.6 C452.129945,297.6 448.901724,294.851978 448.160188,291.200785 L444.639812,291.200785 C443.898276,294.851978 440.670055,297.6 436.8,297.6 C432.929945,297.6 429.701724,294.851978 428.960188,291.200785 L425.439812,291.200785 C424.698276,294.851978 421.470055,297.6 417.6,297.6 C413.729945,297.6 410.501724,294.851978 409.760188,291.200785 L409.6,291.2 L409.6,131.2 L483.2,131.2 Z"></path> 
                  <rect rx="12.8" height="64" width="121.6" y="294.4" x="86.4" stroke-width="12.8" stroke="#60A4F7" id="矩形"></rect> 
                  <rect rx="6.4" height="12.8" width="89.6" y="169.6" x="224" fill="#60A4F7" id="矩形"></rect> 
                  <rect rx="6.4" height="12.8" width="57.6" y="208" x="256" fill="#60A4F7" id="矩形备份"></rect> 
                  <path fill="url(#linearGradient-4)" id="矩形" d="M399.538967,0 L560.226887,-1.0658141e-14 C574.365377,-1.42108547e-14 585.826887,11.4615104 585.826887,25.6 C585.826887,28.2252819 585.423067,30.8349437 584.629591,33.3374428 L553.6,131.2 L553.6,131.2 L339.2,131.2 L375.136262,17.8625572 C378.508621,7.22665582 388.381225,-7.10542736e-15 399.538967,-7.10542736e-15 Z"></path> 
                  <path transform="translate(128, 65.6) scale(-1, 1) translate(-128, -65.6)" fill="#B8DAFF" id="矩形备份-3" d="M60.3389667,0 L221.026887,-1.0658141e-14 C235.165377,-1.42108547e-14 246.626887,11.4615104 246.626887,25.6 C246.626887,28.2252819 246.223067,30.8349437 245.429591,33.3374428 L214.4,131.2 L214.4,131.2 L0,131.2 L35.9362624,17.8625572 C39.3086213,7.22665582 49.1812249,-7.10542736e-15 60.3389667,-7.10542736e-15 Z"></path> 
                  <polygon points="451.2 0 524.8 0 483.2 131.2 409.6 131.2" fill="#D8EBFA" id="矩形"></polygon> 
                </g> 
              </g> 
            </svg>
          </div>
        </div>
      </template>
    </el-table>
    
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      :pager-count="7"
      background
      class="pagination">
    </el-pagination>
    
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="350px">
      <el-form ref="userForm" :model="currentUser" :rules="rules" label-width="70px">
        <div class="form-row">
          <el-form-item label="姓名" required class="form-item">
            <el-input v-model="currentUser.userName" placeholder="请输入姓名"></el-input>
          </el-form-item>
          <el-form-item label="性别" class="form-item">
            <el-select v-model="currentUser.userGender" placeholder="请选择性别">
              <el-option label="男" :value="1"></el-option>
              <el-option label="女" :value="0"></el-option>
              <el-option label="未知" :value="2"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="头像">
          <div class="avatar-section">
            <el-upload
              ref="avatarUpload"
              class="avatar-uploader"
              action="/api/file/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :data="{userAvatar: currentUser.userAvatar}">
              <img v-if="currentUser.userAvatar" :src="currentUser.userAvatar" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <el-button size="small" type="primary" @click="$refs.avatarUpload.$el.querySelector('input').click()" class="upload-button">上传头像</el-button>
          </div>
        </el-form-item>
         <el-form-item label="生日">
           <el-date-picker
             v-model="currentUser.userBirthday"
             type="date"
             placeholder="请选择生日"
             format="YYYY-MM-DD"
             value-format="YYYY-MM-DD"
             style="width: 100%;">
           </el-date-picker>
         </el-form-item>
         <el-form-item label="入职时间">
           <el-date-picker
             v-model="currentUser.userJoinAt"
             type="date"
             placeholder="请选择入职时间"
             format="YYYY-MM-DD"
             value-format="YYYY-MM-DD"
             style="width: 100%;">
           </el-date-picker>
         </el-form-item>
         <el-form-item label="手机号" prop="userMobile">
           <el-input v-model="currentUser.userMobile" placeholder="请输入手机号"></el-input>
         </el-form-item>
         <el-form-item label="邮箱" prop="userEmail">
           <el-input v-model="currentUser.userEmail" placeholder="请输入邮箱"></el-input>
         </el-form-item>
         <el-form-item label="部门名称">
           <el-input v-model="currentUser.userDeptName" placeholder="请输入部门名称"></el-input>
         </el-form-item>
         <el-form-item label="账号状态">
           <el-switch
             v-model="currentUser.userStatus"
             active-text="禁用"
             inactive-text="正常"
             :active-value="true"
             :inactive-value="false">
           </el-switch>
         </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUser">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { RefreshRight, Plus, Search } from '@element-plus/icons-vue'

export default {
  name: 'UserList',
  components: {
    RefreshRight,
    Plus,
    Search
  },
  data() {
    return {
      users: [],
      dialogVisible: false,
      dialogTitle: '',
      currentUser: {
        id: null,
        userName: '',
        userAvatar: '',
        userGender: 2,
        userBirthday: '',
        userJoinAt: '',
        userMobile: '',
        userEmail: '',
        userDeptName: '',
        userStatus: false
      },
      isEdit: false,
      searchName: '',
      searchMobile: '',
      pageNum: 1,
      pageSize: 5,
      total: 0,
      rules: {
        userMobile: [
          { required: false, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        userEmail: [
          { required: false, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.currentUser.userAvatar = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    }
  },
  mounted() {
    // 使用虚拟数据而不是从API获取
    this.users = [
      {
        id: 1,
        userName: '张三',
        userAvatar: 'https://via.placeholder.com/150',
        userGender: 1,
        userBirthday: '1990-01-01',
        userJoinAt: '2020-01-01',
        userMobile: '13800138000',
        userEmail: 'zhangsan@example.com',
        userDeptName: '技术部',
        userStatus: true
      },
      {
        id: 2,
        userName: '李四',
        userAvatar: 'https://via.placeholder.com/150',
        userGender: 2,
        userBirthday: '1992-05-15',
        userJoinAt: '2021-03-10',
        userMobile: '13900139000',
        userEmail: 'lisi@example.com',
        userDeptName: '市场部',
        userStatus: true
      },
      {
        id: 3,
        userName: '王五',
        userAvatar: 'https://via.placeholder.com/150',
        userGender: 1,
        userBirthday: '1988-12-20',
        userJoinAt: '2019-07-01',
        userMobile: '13700137000',
        userEmail: 'wangwu@example.com',
        userDeptName: '人事部',
        userStatus: false
      }
    ];
    this.total = this.users.length;
  },
  methods: {
    fetchUsers() {
      const pageRequest = {
        pageNum: this.pageNum,
        pageSize: this.pageSize
      };
      
      axios.post('/api/user/list', pageRequest, {
        params: {
          name: this.searchName,
          mobile: this.searchMobile
        }
      })
        .then(response => {
          this.users = response.data.users
          this.total = response.data.total
        })
        .catch(error => {
          console.error('获取用户列表失败:', error)
          this.$message.error('获取用户列表失败')
        })
    },
    handleSearch() {
      this.pageNum = 1
      this.fetchUsers()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.pageNum = 1
      this.fetchUsers()
    },
    handleCurrentChange(val) {
      this.pageNum = val
      this.fetchUsers()
    },
    showAddForm() {
      this.dialogTitle = '添加用户'
      this.isEdit = false
      this.currentUser = {
        id: null,
        userName: '',
        userAvatar: '',
        userGender: 2,
        userBirthday: '',
        userJoinAt: '',
        userMobile: '',
        userEmail: '',
        userDeptName: '',
        userStatus: false
      }
      this.$nextTick(() => {
        if (this.$refs.userForm) {
          this.$refs.userForm.clearValidate()
        }
      })
      this.dialogVisible = true
    },
    showEditForm(user) {
      this.dialogTitle = '编辑用户'
      this.isEdit = true
      this.currentUser = { ...user }
      this.$nextTick(() => {
        if (this.$refs.userForm) {
          this.$refs.userForm.clearValidate()
        }
      })
      this.dialogVisible = true
    },
    saveUser() {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            axios.post('/api/user/update', this.currentUser)
              .then(response => {
                if (response.data) {
                  this.$message.success('用户更新成功')
                  this.fetchUsers()
                  this.dialogVisible = false
                } else {
                  this.$message.error('用户更新失败')
                }
              })
              .catch(error => {
                console.error('更新用户失败:', error)
                this.$message.error('更新用户失败')
              })
          } else {
            axios.post('/api/user/save', this.currentUser)
              .then(response => {
                if (response.data) {
                  this.$message.success('用户添加成功')
                  this.fetchUsers()
                  this.dialogVisible = false
                } else {
                  this.$message.error('用户添加失败')
                }
              })
              .catch(error => {
                console.error('添加用户失败:', error)
                this.$message.error('添加用户失败')
              })
          }
        }
      })
    },
    deleteUser(id) {
      this.$confirm('确定要删除这个用户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.post('/api/user/delete', { id: id })
          .then(response => {
            if (response.data) {
              this.$message.success('用户删除成功')
              this.fetchUsers()
            } else {
              this.$message.error('用户删除失败')
            }
          })
          .catch(error => {
            console.error('删除用户失败:', error)
            this.$message.error('删除用户失败')
          })
      })
    }
  }
}
</script>

<style scoped>
.user-management {
  background: #ffffff;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.1);
  height: calc(100vh - 160px);
  display: flex;
  flex-direction: column;
  border: 1px solid #e6e6e6;
  overflow: hidden;
  position: relative;
}

.breadcrumb {
  padding: 12px 16px;
  background: #ffffff;
  box-shadow: 0 2px 6px rgba(0,0,0,.08);
  margin-bottom: 20px;
  border-radius: 8px;
  font-weight: 500;
  border: 1px solid #e6e6e6;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
  padding: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
}

.search {
  display: flex;
  align-items: center;
  gap: 16px;
}

.search-input {
  width: 220px;
}

.search-button {
  border-radius: 6px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.actions .el-button {
  margin-left: 12px;
  border-radius: 6px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.actions .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.actions .el-button:first-child {
  margin-left: 0;
}

.user-table {
  width: 100%;
  margin-top: 16px;
  flex: 1;
  overflow-y: auto;
  border-radius: 8px;
  box-shadow: 0 2px 16px rgba(0, 0, 0, 0.08);
  max-height: calc(100vh - 260px);
  position: relative;
}

.user-table :deep(.el-table__empty-block) {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100% !important;
  min-height: 300px;
}

.user-table :deep(.el-table__header) th {
  background-color: #f0f8ff;
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.user-table .el-table__row:hover {
  cursor: pointer;
}

.empty-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  width: 100%;
}

.empty-icon {
  display: flex;
  align-items: center;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 20px 0 0;
  border-top: 1px solid #eaeaea;
}

.dialog-footer .el-button {
  margin-left: 12px;
  border-radius: 6px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.dialog-footer .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 16px 0;
  background: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.form-row {
  display: flex;
  gap: 20px;
}

.form-item {
  flex: 1;
}

.avatar-section {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 15px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: inline-block;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
}

.avatar {
  width: 80px;
  height: 80px;
  display: block;
  border-radius: 50%;
}

.upload-button {
  margin: 0;
  align-self: flex-start;
  margin-top: 30px;
}
</style>